package com.example.train.common.exception.handler;

import com.example.train.common.base.model.ResponseBase;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Description: 全局的异常处理
 * @Date: 18-10-31 19:00
 */
@ControllerAdvice
@Slf4j
public class MVCGlobalExceptionHandler {
    /**
     * 参数校验统一异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseBase handleBindException(MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        log.warn("参数校验异常:{}({})", fieldError.getDefaultMessage(),fieldError.getField());
        return ResponseBase.validateFailed(fieldError.getField()+fieldError.getDefaultMessage());
    }

}
